<template>
  <div class="Employees-container">
    <el-table :data="filterList[page - 1]" :default-sort = "{prop: 'date', order: 'descending'}">
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="职工姓名" prop="name"></el-table-column>
      <el-table-column label="职工邮箱" prop="email"></el-table-column>
      <el-table-column label="职工权限">
        <template #default="{ row }">
          <div>
            {{ row.role | roleFormat }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
      prop="date"
      label="注册时间"
      sortable
      >
        <template #default="{ row }">
          <div>
            {{ row.date | dateFormat }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <div>
            <router-link :to="'/index/detail/' + row.id">详情</router-link>&nbsp;
            <!-- <a href="#" @click.prevent="onremove(row.id)">删除</a> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination 
    @size-change="handleSizeChange" 
    @current-change="handleCurrentChange" 
    :current-page="1" :page-sizes="[5, 10, 15, 20]" 
    :page-size="5" layout="total, sizes, prev, pager, next, jumper" 
    :total="userlist.length">
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: 'Employees',
  data() {
    return {
      userlist: [],
      limit: 5,
      page: 1
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('/api/employees')
      if (res.status === 1) return this.$message(res.message)
      this.userlist = res
    },
    onremove() {},
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.limit = val
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
    },
    chunk(array, size) {
      const length = array.length
      if (!length || !size || size < 1) {
        return []
      }
      let index = 0 //用来表示切割元素的范围start
      let resIndex = 0 //用来递增表示输出数组的下标
      let result = new Array(Math.ceil(length / size))
      while (index < length) {
        result[resIndex++] = array.slice(index, (index += size))
      }
      return result
    },
  },
  computed: {
    filterList() {
      return this.chunk(this.userlist, this.limit)
    },
  },
  filters: {
    dateFormat(str) {
      var dt = new Date(str)
      var y = dt.getFullYear()
      var m = dt.getMonth() + 1
      var d = dt.getDate()
      var h = dt.getHours()
      var mm = dt.getMinutes()
      var s = dt.getSeconds()
      return `${y}-${m}-${d}`
    },
  },
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin: 30px 0 0 970px;
}
</style>
